<template>
  <div class="dg-row dg-body-cell" :style="cellStyle" @mouseover="onRowMouseOver(node)" @mouseout="onRowMouseOut(node)" @click="onRowClick(node)">
    <div class="dg-check" v-if="column.checkbox">
      <checkbox :disabled="node.checkDisabled" :value="node.checked" @input="onCheckStateChange"></checkbox>
    </div>
    <template v-if="!column.cellTemplate">
      {{displayValue}}
    </template>
    <div ref="cellTemplate" v-if="column.cellTemplate">
    </div>
  </div>
</template>

<script>
  import _ from 'lodash'
  import Vue from 'vue'
  import Checkbox from '../components/Checkbox.vue'
  export default {
    components: {Checkbox},
    props: {
      rootConfig: {
        type: Object,
        default () {
          return {}
        }
      },
      column: Object,
      node: Object
    },
    data () {
      return {
        selected: false
      }
    },
    computed: {
      displayValue () {
        let val = this.node.data[this.column.field]
        if (this.column.cellRenderer && _.isFunction(this.column.cellRenderer)) {
          return this.column.cellRenderer(val, this.node, this.column)
        }
        return val
      },
      cellStyle () {
        return {
          'padding-left': `${this.column.checkbox ? '38px' : null}`
        }
      }
    },
    methods: {
      onCheckStateChange (checked) {
        Vue.set(this.node, 'checked', checked)
        this.$emit('check', this.node)
        if (!this.rootConfig.selectionNotEqualsChecking) {
          Vue.set(this.node, 'selected', this.node.checked)
        }
      },
      onRowMouseOver () {
        this.$emit('mouseover', this.node)
      },
      onRowMouseOut () {
        this.$emit('mouseout', this.node)
      },
      onRowClick () {
        this.$emit('click', this.node)
      }
    },
    mounted () {
      this.node._$vm = this
      let self = this
      if (this.column.cellTemplate) {
        new Vue({
          el: this.$refs.cellTemplate,
          data: {
            data: this.node
          },
          beforeCreate () {
            this.$options.template = self.column.cellTemplate
            if (self.column.context) {
              if (!this.$options.methods) {
                this.$options.methods = {}
              }
              _.forOwn(self.column.context, (v, k) => {
                if (_.isFunction(v)) {
                  this.$options.methods[k] = v
                } else {
                  this.$options.data[k] = v
                }
              })
            }
          }
        })
      }
    },
    destroyed () {
      delete this.node._$vm
    }
  }
</script>

<style>
  .dg-body-cell{
    position: relative;
    padding: 4px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .dg-check{
    position: absolute;
    left: 8px;
    line-height: 0 !important;
    top: 50%;
    transform: translateY(-50%);
  }
</style>